package net.plankton.mjpeg;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;


public class ReadCam implements JpegProvider{

	private InputStream stream;
	
	public ReadCam(InputStream stream) {
		this.stream = stream;
	}
	
	public byte[] next() throws Exception {
		alternate = !alternate;
		if (alternate) {
			return readImage(stream);
		}
		
		else {
			return new byte[] {0,0};
		}
	}
	
boolean alternate=false;
	
	public byte[] readImage(InputStream stream) throws Exception{
//		for (int i=0;i<20;i++)  {
//			System.err.println((char)stream.read());
//		}
stream.skip(30);
		StringBuilder b = readInt(stream);
		int size =0;
		try {
			size = Integer.parseInt(b.toString());
		}
		catch (Exception e) {
			 b = readInt(stream);
			size = Integer.parseInt(b.toString());
		}
//		System.err.println("size: "+size);
		stream.skip(3);
		byte[] by = new byte[size];
		int count = 0;
		while (stream.available()<size) {
//			System.err.println("waiting");
			if (count++>1000) {
				stream.close();
				throw new Exception();
			}
				
			Thread.sleep(10);
		}
		int num = stream.read(by);
		while (num!=size) {	
			stream.read(by, num, size-num);
		}
//		System.err.println("exit");
		return by;
	}

	private StringBuilder readInt(InputStream stream) throws Exception {
		int i = stream.read();
		if (i==-1)  {
			for (int j=0;j<20000;j++) {
				i = stream.read();
				if (i!=-1)
					break;
			}
			if (i==-1) {
				System.err.println("end");
				throw new Exception();
			}
		}
		
		StringBuilder b = new StringBuilder();
		while (i!=13) {
//			System.err.println((char)i+" "+i);
			if (i>47 && i<58)
				b.append((char)i);
			i = stream.read();
		}
		return b;
	}
	
}
